#coding=utf-8
import ffmpeg
import os,subprocess


# 创建音频图
def create_audio_img(input_file, output_file, sate='640x120', aframes=1):
    if not os.path.exists(input_file):
        return False
    out, err = (
        ffmpeg
            .input(input_file)
            .output(output_file, filter_complex='showwavespic=s=' + sate, aframes=aframes)
            .run(overwrite_output=True)
    )
    if err:
        return False
    return True


# 音频裁剪
def audio_cut(input_file, output_file, ss=0, to=5, acodec='copy'):
    out, err = (
        ffmpeg
            .input(input_file)
            .output(output_file, acodec=acodec, ss=ss, t=to)
            .run(overwrite_output=True)
    )
    if err:
        return False
    return output_file


# 拼接音频
def audio_concat(files_arr):
    if not isinstance(files_arr, list):
        return False
    for file in files_arr:
        if not os.path.exists(file):
            return False
    return sample_rate(files_arr)


# 格式化音频，获取最低/最高采样率并设置
def sample_rate(files_arr, default_sample_rate='min'):
    files_dict = {}
    need_contact = []
    shot_name_arr = []
    dirname = ''
    extension = ''
    for file in files_arr:
        info = next(c for c in ffmpeg.probe(file)['streams'])
        base_name = os.path.basename(file)
        dirname, tmp_filename = os.path.split(file)
        shot_name, extension = os.path.splitext(tmp_filename)
        shot_name_arr.append(shot_name)
        files_dict[base_name] = info['sample_rate']
    # 最小、最大采样率
    if default_sample_rate and default_sample_rate in ['max', 'min']:
        if default_sample_rate == 'max':
            sample_rate = max(files_dict.values())
        else:
            sample_rate = min(files_dict.values())
    else:
        return False
    # 按需格式化
    for item in files_dict.items():
        filepath = dirname + '/' + item[0]
        if item[1] != sample_rate:
            output_filepath = dirname + '/tmp_' + item[0]
            need_contact.append(output_filepath)
            out, err = (
                ffmpeg
                    .input(filepath)
                    .output(output_filepath, ar=sample_rate)
                    .run(overwrite_output=True)
            )
            if err:
                return False
        else:
            need_contact.append(filepath)
    # 合并
    input_file = 'concat:' + '|'.join(need_contact)
    output_file = dirname + '/' + '_'.join(shot_name_arr) + extension
    out, err = (
        ffmpeg
            .input(input_file)
            .output(output_file, acodec='copy')
            .run(overwrite_output=True)
    )
    if err:
        return False
    return output_file

def format(input_file, output_file, f='wav', ar='16000'):
    out, err = (
        ffmpeg
            .input(input_file)
            .output(output_file, f=f, ar=ar)
            .run(overwrite_output=True)
    )
    if err:
        return False
    return output_file


def info(audio, param=None):
    info = ffmpeg.probe(audio)
    vs = next(c for c in info['streams'])
    if param:
        return float(vs['duration'])
    return vs


# 生成无声音频 （t 时长；；ar频率；cl：mono单声道,stereo双声道）
def acc_audio(output, t, ar=16000, cl='mono'):
    command = 'ffmpeg -f lavfi -t '+ str(t) + ' -i anullsrc=r=' + str(ar) + ':cl=' + cl  + ' ' + output + ' -y'
    print(command)
    if subprocess.Popen(command, shell=True).wait():
        return False
    return output